import os
import time

if os.name == "posix":
    cache_save_dir = "/tmp"
else:
    cache_save_dir = ""


class PrintLoggerMgr:
    level = 30
    cache = list()
    cache_limit = 1000
    save_dir = cache_save_dir

    @classmethod
    def set_save_dir(cls, _dir: str):
        if os.path.exists(_dir):
            cls.save_dir = _dir
        else:
            print(f"文件夹不存在：{_dir}")

    @classmethod
    def set_level(cls, level_num: int):
        cls.level = level_num

    @classmethod
    def set_cache_limit(cls, cache_limit_num: int):
        cls.cache_limit = cache_limit_num
    @classmethod
    def append_log(cls, _log: str):
        cls.cache.append(_log)
        if len(cls.cache) > cls.cache_limit:
            cls.cache.pop(0)
    
    @classmethod
    def clear_cache(cls):
        if os.path.exists(cls.save_dir):
            temp_log_file = os.path.join(cls.save_dir,
                                         f"print_log_{time.strftime('%Y-%m-%d_%H:%M:%S', time.localtime())}.log")
            with open(temp_log_file, "a") as f:
                f.writelines(cls.cache)
        cls.cache.clear()

    @classmethod
    def is_empty(cls):
        if len(cls.cache):
            return False
        else:
            return True

    @classmethod
    def last_log(cls):
        if cls.is_empty():
            return ""
        else:
            return cls.cache[-1]

    @classmethod
    def contains(cls, expect_str: str):
        for _log in cls.cache:
            if expect_str in _log:
                return True
        return False

def my_debug(*args):
    if PrintLoggerMgr.level <= 10:
        _log = "[DEBUG]::"
        for arg in args:
            _log = _log + f"{arg}"
        print(_log)
        PrintLoggerMgr.append_log(_log + "\n")

def my_info(*args):
    if PrintLoggerMgr.level <= 20:
        _log = "[INFO]::"
        for arg in args:
            _log = _log + f"{arg}"
        print(_log)
        PrintLoggerMgr.append_log(_log + "\n")
            
def my_warning(*args):
    if PrintLoggerMgr.level <= 40:
        _log = "[WARNING]::"
        for arg in args:
            _log = _log + f"{arg}"
        print(_log)
        PrintLoggerMgr.append_log(_log + "\n")

def my_error(*args):
    if PrintLoggerMgr.level <= 50:
        _log = "[ERROR]::"
        for arg in args:
            _log = _log + f"{arg}"
        print(_log)
        PrintLoggerMgr.append_log(_log + "\n")


def my_system(*args):
    if PrintLoggerMgr.level <= 55:
        _log = "[SYSTEM]::"
        for arg in args:
            _log = _log + f"{arg}"
        print(_log)
        PrintLoggerMgr.append_log(_log + "\n")


class PrintLogger:
    debug = my_debug
    info = my_info
    warning = my_warning
    warn = my_warning
    error = my_error
    system = my_system